package com.yunkaweilai.android.activity.operation.consumption.shops;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.adapter.multilayout.ShopAdapterItem;
import com.yunkaweilai.android.adapter.multilayout.TimeAdapterItem;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.SimpleInterface;
import com.yunkaweilai.android.interfaces.UpdateGoodsNumInterfaces;
import com.yunkaweilai.android.interfaces.adapter.ShopItemInterface;
import com.yunkaweilai.android.interfaces.adapter.TimeItemInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.PayTypeModel;
import com.yunkaweilai.android.model.shop.SearchShopModel;
import com.yunkaweilai.android.model.shop.ShopSkuInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.zxing.Kutils;
import com.yunkaweilai.android.view.dialog.GoodsStockZeroDialog2;
import com.yunkaweilai.android.view.dialog.UpdateSearchGoodsNumDialog;
import com.zhy.adapter.abslistview.MultiItemTypeAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 商品计次搜索
 * Created by Administrator on 2017/7/19.
 */

public class ShopOrTimeSearchActivity extends BaseActivity implements TimeItemInterface, ShopItemInterface, SimpleInterface, UpdateGoodsNumInterfaces {

    @BindView(R.id.id_edt_search)
    EditText idEdtSearch;
    @BindView(R.id.id_img_clean)
    ImageView idImgClean;
    @BindView(R.id.id_listView_search)
    ListView idListViewSearch;
    private ShopAdapter shopAdapter;
    private ArrayList<SearchShopModel.DataBean.GoodsListBean> searchList = new ArrayList<>();
    private Map<String, ShopSkuInfoModel> selectedMaps;
    private String type;
    public static final String QR_SCAN_TYPE2 = "QR_SCAN_TYPE2";
    private PayTypeModel payTypeModel = BaseApplication.payModel;

    public static void actionStart(Context context, String type) {
        Intent intent = new Intent(context, ShopOrTimeSearchActivity.class);
        intent.putExtra(QR_SCAN_TYPE2, type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_search);
        ButterKnife.bind(this);

        type = getIntent().getStringExtra(QR_SCAN_TYPE2);
        selectedMaps = BaseApplication.getSelectedMaps();
        new TitleBuilder(mAc).setTitleText("搜索商品")
                .setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setRightText("确定").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addShop();
            }
        });
        idEdtSearch.setHint("请输入名称/条码");
        initAdapter();
        initClick();
        Utils.autoShowKeyboard(idEdtSearch);
    }

    //商品加入购物车
    private void addShop() {
        for (int i = 0; i < searchList.size(); i++) {
            SearchShopModel.DataBean.GoodsListBean goodsListBean = searchList.get(i);
            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(goodsListBean.getGoods_sku());
            if (shopSkuInfoModel == null) {
                shopSkuInfoModel = createSkuModel(goodsListBean.getStock(), goodsListBean.getGoods_type(), goodsListBean.getGoods_image(), goodsListBean.getBuy_num(), goodsListBean.getId(), goodsListBean.getGoods_sku(), goodsListBean.getGoods_name()
                        , goodsListBean.getGoods_shop_price(), goodsListBean.getGoods_category_parent_id());
                selectedMaps.put(goodsListBean.getGoods_sku(), shopSkuInfoModel);
            } else {
                shopSkuInfoModel.setBuy_num(goodsListBean.getBuy_num());
            }
        }
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
        finish();
    }

    @Override
    public void refreshGoods() {
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
        shopAdapter.notifyDataSetChanged();
    }


    class ShopAdapter extends MultiItemTypeAdapter<SearchShopModel.DataBean.GoodsListBean> {
        public ShopAdapter(Context context, List<SearchShopModel.DataBean.GoodsListBean> datas) {
            super(context, datas);
            addItemViewDelegate(new TimeAdapterItem(ShopOrTimeSearchActivity.this));
            addItemViewDelegate(new ShopAdapterItem(ShopOrTimeSearchActivity.this));
        }
    }

    private void initAdapter() {
        shopAdapter = new ShopAdapter(mAc, searchList);
        idListViewSearch.setAdapter(shopAdapter);
    }

    //创建商品model，用于全局记录
    private ShopSkuInfoModel createSkuModel(String stock, String type, String url, double buy_num, String id, String sku, String good_name, String shop_price, String goods_category_parent_id) {
        ShopSkuInfoModel shopSkuInfoModel = new ShopSkuInfoModel();
        shopSkuInfoModel.setBuy_num(buy_num);
        shopSkuInfoModel.setSku_id(id);
        shopSkuInfoModel.setSku(sku);
        shopSkuInfoModel.setSku_name(good_name);
        shopSkuInfoModel.setGoods_type(type);
        shopSkuInfoModel.setAdvUrl(url);
        shopSkuInfoModel.setShop_price(Float.parseFloat(shop_price));
        shopSkuInfoModel.setGoods_category_parent_id(goods_category_parent_id);
        shopSkuInfoModel.setSpec_str_md5("");
        if ("Putong".equals(type)) {
            shopSkuInfoModel.setMay_use_stock(Double.parseDouble(stock));
        } else {
            shopSkuInfoModel.setMay_use_stock(9999);
        }
        return shopSkuInfoModel;
    }


    private void initClick() {
        idEdtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null && idEdtSearch.length() > 0) {
                    //点击搜索要做的操作
                    initSearch(idEdtSearch.getText().toString());
                    InputMethodUtils.closeSoftKeyboard(mAc);
                }
                return false;
            }
        });
        idEdtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    idImgClean.setVisibility(View.GONE);
                    return;
                } else {
                    idImgClean.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        idImgClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idImgClean.setVisibility(View.GONE);
                idEdtSearch.setText("");
                searchList.clear();
                shopAdapter.notifyDataSetChanged();
            }
        });

    }

    private void initSearch(String keyword) {
        HttpRequest.postUrl(Api.SEARCH_QR_SHOP)
                .addParams("keyword", keyword)
                .addParams("ScanGoodsType", type)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            SearchShopModel searchShopModel = gson.fromJson(json, SearchShopModel.class);
                            searchList.clear();
                            searchList.addAll(searchShopModel.getData().getGoodsList());
                            for (int i = 0; i < searchList.size(); i++) {
                                SearchShopModel.DataBean.GoodsListBean goodsListBean = searchList.get(i);
                                ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(goodsListBean.getGoods_sku());
                                if (shopSkuInfoModel != null) {
                                    goodsListBean.setBuy_num(shopSkuInfoModel.getBuy_num());
                                } else {
                                    goodsListBean.setBuy_num(0);
                                }
                            }

                            shopAdapter.notifyDataSetChanged();
                            if (searchList.size() == 0) {
                                showToast("暂无此商品");
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(R.string.http_error);
                    }
                });
    }


    @Override
    public void TimeConvert(ViewHolder viewHolder, final SearchShopModel.DataBean.GoodsListBean item, final int position) {
        ImageView mIdImg = viewHolder.getView(R.id.id_img);
        Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);
        viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
        viewHolder.setText(R.id.id_tv_price, item.getGoods_shop_price() + "");
        viewHolder.setText(R.id.id_tv_unit, "/" + item.getUnit());
        ImageView idImgAdd = viewHolder.getView(R.id.id_img_add);
        ImageView idImgDel = viewHolder.getView(R.id.id_img_del);
        TextView idTvAddNum = viewHolder.getView(R.id.id_tv_add_num);
        if (item.getBuy_num() > 0) {
            idImgDel.setVisibility(View.VISIBLE);
            idTvAddNum.setText(Utils.MoneyQuZheng(item.getBuy_num()) + "");
            idTvAddNum.setVisibility(View.VISIBLE);
        } else {
            idImgDel.setVisibility(View.GONE);
            idTvAddNum.setText("0");
            idTvAddNum.setVisibility(View.GONE);
        }

        idTvAddNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateSearchGoodsNumDialog dialog = new UpdateSearchGoodsNumDialog(mAc, item, ShopOrTimeSearchActivity.this, "修改数量");
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }
        });
        //增加
        idImgAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                item.setBuy_num(item.getBuy_num() + 1);
                shopAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
            }
        });


        //减少
        idImgDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getBuy_num() > 0) {
                    item.setBuy_num(item.getBuy_num() - 1);
                } else {
                    item.setBuy_num(0);
                }
                shopAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
            }
        });
    }

    @Override
    public void ShopConvert(ViewHolder viewHolder, final SearchShopModel.DataBean.GoodsListBean item, final int position) {
        ImageView mIdImg = viewHolder.getView(R.id.id_img);
        Utils.shopInfoImg(mAc, item.getGoods_image(), mIdImg);
        viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
        viewHolder.setText(R.id.id_tv_price, item.getGoods_shop_price());
        viewHolder.setText(R.id.id_tv_unit, "/" + item.getUnit());
        viewHolder.setText(R.id.id_tv_info, "库存：" + item.getStock());

        ImageView idImgAdd = viewHolder.getView(R.id.id_img_add);
        ImageView idImgDel = viewHolder.getView(R.id.id_img_del);
        TextView idTvAddNum = viewHolder.getView(R.id.id_tv_add_num);
        if (item.getBuy_num() > 0) {
            idImgDel.setVisibility(View.VISIBLE);
            idTvAddNum.setText(Utils.MoneyQuZheng(item.getBuy_num()) + "");
            idTvAddNum.setVisibility(View.VISIBLE);
        } else {
            idImgDel.setVisibility(View.GONE);
            idTvAddNum.setText("0");
            idTvAddNum.setVisibility(View.GONE);
        }

        idTvAddNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateSearchGoodsNumDialog dialog = new UpdateSearchGoodsNumDialog(mAc, item, ShopOrTimeSearchActivity.this, "修改数量");
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }
        });

        //增加
        idImgAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getBuy_num() + 1 > Float.parseFloat(item.getStock()) && "0".equals(payTypeModel.getData().getInfo().getIs_open_stock())) {
                    GoodsStockZeroDialog2 dialog2 = new GoodsStockZeroDialog2(mAc, ShopOrTimeSearchActivity.this, item);
                    dialog2.setCanceledOnTouchOutside(false);
                    dialog2.show();
                } else {
                    item.setBuy_num(Kutils.add(item.getBuy_num(), 1));
                    shopAdapter.notifyDataSetChanged();
                    EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
                }
            }
        });

        //减少
        idImgDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getBuy_num() > 0) {
                    item.setBuy_num(Kutils.sub(item.getBuy_num(), 1));
                } else {
                    item.setBuy_num(0);
                }
                shopAdapter.notifyDataSetChanged();
                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));

            }
        });
    }

    @Override
    public void nothing() {
        shopAdapter.notifyDataSetChanged();
        EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
    }

}
